import React, { useState } from "react";
import {
  DesktopOutlined,
  FileOutlined,
  PieChartOutlined,
  TeamOutlined,
  UserOutlined,
} from "@ant-design/icons";
import type { MenuProps } from "antd";
import { Menu } from "antd";
import { useNavigate ,useLocation} from "react-router-dom";
type MenuItem = Required<MenuProps>["items"][number];
const items:MenuItem[] = [
    {
        label:"菜单1",
        key:"/page1",
        icon:<PieChartOutlined />
    },
    {
        label:"菜单2",
        key:"/page2",
        icon:<DesktopOutlined />
    },
    {
        label:"菜单3",
        key:"/page3",
        icon:<UserOutlined />,
        children:[
            {
                label:"子菜单1",
                key:"/page3/page301",
            },
            {
                label:"子菜单2",
                key:"/page3/page302",
            },
            {
                label:"子菜单3",
                key:"/page3/page303",
            },
        ]
    },
    {
        label:"菜单4",
        key:"/page4",
        icon:<TeamOutlined />,
        children:[
            {
                label:"子菜单1",
                key:"/page4/page401",
            },
            {
                label:"子菜单2",
                key:"/page4/page402",
            },
            {
                label:"子菜单3",
                key:"/page4/page403",
            },
        ]
    },
    {
        label:"菜单5",
        key:"/page5",
        icon:<FileOutlined />
    },
]
const View: React.FC = () => {
  const navigateTo = useNavigate();
  const currentRoute = useLocation();
  const menuClickHandler = (e: { key: string }) => {
    navigateTo(e.key);
  };
  
let firstOpenKey:string = ""
const findKey = (item:MenuItem) =>{
    return item!.key === currentRoute.pathname
} 

for (let i = 0; i < items.length; i++) {
    // @ts-ignore
    if(items[i]['children'] && items[i]['children'].length > 0 && items[i]['children'].find(findKey)){
        firstOpenKey = items[i]!.key as string;
        break;
    }
}
const [openKeys, setOpenKeys] = useState([firstOpenKey]);
  
  const onOpenChange: MenuProps["onOpenChange"] = (keys) => {
    setOpenKeys([keys[keys.length - 1]]);
  };
  return (
    <Menu
      theme="dark"
      defaultSelectedKeys={[currentRoute.pathname]}
      mode="inline"
      items={items}
      openKeys={openKeys}
      onClick={menuClickHandler}
      onOpenChange={onOpenChange}
    />
  );
};

export default View;
